package com.blog.spring;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;

/**
 * @author 刘会俊
 * @description
 * @date 2019-10-04 16:04
 */
public class MyApplicationAware implements BeanNameAware, BeanFactoryAware, BeanClassLoaderAware, ApplicationContextAware {

    private String beanNam;

    private BeanFactory beanFactory;

    private ClassLoader classLoader;

    private ApplicationContext applicationContext;

    @Override
    public void setBeanClassLoader(ClassLoader classLoader) {
        System.out.println("ClassLoader");
        this.classLoader = classLoader;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("BeanFacory");
        this.beanFactory = beanFactory;
    }

    @Override
    public void setBeanName(String name) {
        System.out.println("BeanName");
        this.beanNam = name;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("ApplicationContext");
        this.applicationContext = applicationContext;
    }

    public void display() {
        System.out.println("beanname=" + beanNam);
        System.out.println("是否为单例：" + beanFactory.isSingleton(beanNam));
        System.out.println("系统环境" + applicationContext.getEnvironment());
    }

    public static void main(String[] args) {
        /*ClassPathResource classPathResource = new ClassPathResource("spring.xml");
        DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
        reader.loadBeanDefinitions(classPathResource);

        MyApplicationAware applicationAware = (MyApplicationAware) factory.getBean("myApplicationAware");
        applicationAware.display();*/

        //上面只运行了三个 aware接口的方法

        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        MyApplicationAware myApplicationAware = (MyApplicationAware) applicationContext.getBean("myApplicationAware");
        myApplicationAware.display();
        //上面的运行了四个aware接口的方法

        //原因：通过getBean()获取bean时，只检测了BeanNameAware, BeanFactoryAware, BeanClassLoaderAware三个接口的实现，如果实现了回调方法则将对应的aware
        //设置给该bean，这个是bean就从Spring 容器中获得相应的资源


    }
}
